package cn.gov.pbc.exam.excel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import cn.gov.pbc.exam.common.ServerResponse;
import lombok.Getter;

@Getter
public class QuestionExcelListener extends AnalysisEventListener<QuestionExcelDto> {
	
	private List<QuestionExcelDto> questionList;
	
	private List<QuestionDto> questionDtoList;
	
	private Integer rowIndex = 2;
	
	public QuestionExcelListener() {
		this.questionList = new ArrayList<>();
		this.questionDtoList = new ArrayList<>();
	}
	
	

	@Override
	public void invoke(QuestionExcelDto data, AnalysisContext context) {
		ServerResponse<?> response;
		if(StringUtils.isNotBlank(data.getQuestion()) && questionList.size() > 0) {
			response = QuestionDto.addQuestionDto(this.questionList);
			if(!response.isSuccess()) {
				throw new RuntimeException("excel中第" + this.rowIndex + "错误:" + response.getMsg());
			}
			this.questionDtoList.add((QuestionDto)response.getData());
			this.questionList.clear();
		}
		this.questionList.add(data);
		this.rowIndex++;
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext context) {
		ServerResponse<?> response = QuestionDto.addQuestionDto(this.questionList);
		if(!response.isSuccess()) {
			throw new RuntimeException("excel中第" + this.rowIndex + "错误:" + response.getMsg());
		}
		this.questionDtoList.add((QuestionDto)response.getData());
		this.questionList.clear();
	}




	@Override
	public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
		if(headMap.size() != 6) {
			throw new RuntimeException("表格式错误，请严格使用模板导入");
		}
		for(Map.Entry<Integer, String> item : headMap.entrySet()) {
			switch (item.getKey()) {
			case 0:
				if(!item.getValue().equals("序号")) {
					throw new RuntimeException("表格式错误，第一列表头" + item.getValue());
				}
				break;
			case 1:
				if(!item.getValue().equals("题目")) {
					throw new RuntimeException("表格式错误，第二列表头" + item.getValue());
				}
				break;
			case 2:
				if(!item.getValue().equals("题目类型")) {
					throw new RuntimeException("表格式错误，第三列表头" + item.getValue());
				}
				break;
			case 3:
				if(!item.getValue().equals("选项标题")) {
					throw new RuntimeException("表格式错误，第四列表头" + item.getValue());
				}
				break;
			case 4:
				if(!item.getValue().equals("选项内容")) {
					throw new RuntimeException("表格式错误，第五列表头" + item.getValue());
				}
				break;
			case 5:
				if(!item.getValue().equals("是否为正确答案")) {
					throw new RuntimeException("表格式错误，第六列表头" + item.getValue());
				}
				break;
			default:
				throw new RuntimeException("表格式错误，请严格使用模板导入");
			}
		}
				
		super.invokeHeadMap(headMap, context);
		
	}

}
